package cube.utils.comp;

import cube.utils.BeanUtil;

/**
 * 列表排序器
 * 
 * @author abiao
 */
public class Comparator<T> implements java.util.Comparator<T> {

	/**
	 * 默认升序
	 */
	private static final Order DEFAULT_ORDER = Order.ASC;
	private String propName;
	private int ordernum;

	/**
	 * @param propName
	 *            排序属性名称
	 */
	public Comparator(String propName) {
		this(propName, DEFAULT_ORDER);
	}

	/**
	 * @param propName
	 *            排序属性名称
	 * @param order
	 *            顺序
	 */
	public Comparator(String propName, Order order) {
		this.propName = propName;
		this.ordernum = (order == DEFAULT_ORDER ? 1 : -1);
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	@Override
	public int compare(T o1, T o2) {
		int comparenum = -1;
		Object v1 = BeanUtil.readValue(o1, propName);
		Object v2 = BeanUtil.readValue(o2, propName);
		if (comparables(v1, v2)) {
			comparenum = ((Comparable<Object>) v1).compareTo(v2);
		}
		return ordernum * comparenum;
	}

	/**
	 * 是否具有可比性
	 */
	private boolean comparables(Object v1, Object v2) {
		return v1 != null && v2 != null && v1 instanceof Comparable
				&& v2 instanceof Comparable;
	}
}
